<template>
  <div class="use-car">
    <div class="card">
      <el-form inline>
        <el-form-item label="用车人姓名：">
          <el-input v-model="params.name" placeholder="请输入用车人姓名" />
        </el-form-item>

        <el-form-item label="审核状态：">
          <el-select
            v-model="params.review_status"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in examineStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <!--        <el-table-column prop="id" label="ID" align="center" />-->

        <el-table-column prop="user.username" label="用车人" align="center" />

        <el-table-column prop="driver_type" label="驾驶员类型" align="center">
          <template v-slot="{ row }">
            {{ driverType[row.driver_type] ?? '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="driver_name" label="司机姓名" align="center">
          <template v-slot="{ row }">
            <div v-if="row.driver_name">
              {{ row.driver_name }}
            </div>

            <div v-else-if="row.driver_user">
              {{ row?.driver_user?.username }}
            </div>

            <el-tag v-if="row.vehicle?.type?.type === 'noDriver'">自驾车</el-tag>

            <!--            <el-tag v-if="row.is_need_driver === 0 && row.vehicle?.type?.type !== 'noDriver'">无需司机</el-tag>-->
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="申请时间" align="center">
          <template v-slot="{ row }">
            {{ timeFormat(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column prop="car_reason" label="用车原因" align="center" show-overflow-tooltip />

        <el-table-column prop="vehicle_route" label="用车路线" align="center" show-overflow-tooltip />

        <el-table-column prop="vehicle_usage_time" label="用车时间" align="center">
          <template v-slot="{ row }">
            {{ timeFormat(row.vehicle_usage_time) }}
          </template>
        </el-table-column>

        <el-table-column prop="vehicle" label="车辆信息" align="center">
          <template v-slot="{ row }">
            <el-button type="text" @click="openVehicleDialog(row.vehicle)">点击查看</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="review_status" label="审核状态" align="center">
          <template v-slot="{ row }">
            <el-tag :type="stateTagOptions(row.cance ? 2 : row.review_status).type">
              {{ stateTagOptions(row.cance ? 2 : row.review_status).label }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />

        <el-table-column prop="created_at" label="审核时间" align="center">
          <template v-slot="{ row }">
            <span v-if="stateFormatter(row.review_status) === 'wait'">-</span>
            <span
              v-else
            >
              {{ timeFormat(row.revuew_time || row.updated_at) }}
            </span>
            <span v-if="row.review_status === null">-</span>
          </template>
        </el-table-column>

        <el-table-column prop="review_status" label="操作" align="center">
          <template v-slot="{ row }">
            <el-button type="text" @click="openExamineDrawer(row)">
              查看
            </el-button>
            <el-button
              v-if="editBtnVisible(row)"
              type="text"
              @click="handleShowEditBtn(row)"
            >
              编辑
            </el-button>
            <el-button
              style="color: #FF4949;"
              type="text"
              @click="handleDeleteRecord(row.id)"
            >
              删除
            </el-button>
            <!--            <el-button-->
            <!--              v-if="stateTagOptions(row.cance ? 2 : row.review_status).type === 'wait'-->
            <!--                || stateTagOptions(row.cance ? 2 : row.review_status).type === 'success'"-->
            <!--              type="text"-->
            <!--              @click="handleCancelRecord(row.id)"-->
            <!--            >-->
            <!--              撤销-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <Pagination
          v-if="total"
          style="margin-top: 0; padding-bottom: 0;"
          :total="total"
          :limit="params.paginate"
          :page="params.page"
          @pagination="pagination"
        />
      </div>

    </el-card>

    <VehicleDetailDialog
      v-model="vehicleDialogShow"
      :vehicle-info="vehicleInfo"
    />

    <UseCarDetailDrawer
      :visible.sync="useCarRecordingDrawVisible"
      :record-id="currentRecording"
      @examine="handleExamine"
    />

    <EditCarUse
      v-model="editCarUseInfo"
      :visible.sync="editCarUseVisible"
      @confirm="handleEditCarUseConfirm"
    />
  </div>
</template>

<script>
import {
  examineUseVehicle,
  getUseCarRecordList,
  deleteVehicleRecords,
  cancelVehicleRecords,
  editCarUseByAdmin
} from '@/api/vehicleService'
import VehicleDetailDialog from '@/views/vehicleService/components/useCarApplication/VehicleDetailDialog.vue'
import UseCarDetailDrawer from '@/views/vehicleService/components/useCarApplication/UseCarDetailDrawer.vue'
import Pagination from '@/components/Pagination'
import dayjs from 'dayjs'
import EditCarUse from '@/views/vehicleService/components/useCarApplication/EditCarUse.vue'
export default {
  name: '',
  components: {
    VehicleDetailDialog,
    UseCarDetailDrawer,
    Pagination,
    EditCarUse
  },
  data() {
    return {
      loading: false,
      list: [],
      vehicleDialogShow: false,
      vehicleInfo: {},
      useCarRecordingDrawVisible: false,
      currentRecording: null,
      total: 0,
      params: {
        paginate: 10,
        page: 1,
        name: '',
        user_id: '',
        vehicle_resources_id: '',
        review_status: ''
      },
      examineStatus: [
        { label: '待审核', value: 'null' },
        { label: '审核通过', value: 1 },
        { label: '审核不通过', value: 'fail' }
      ],
      driverType: {
        driver: '司机',
        self: '本人',
        notSelf: '非本人'
      },
      editCarUseVisible: false,
      editCarUseInfo: null
    }
  },
  created() {
    this.getRecordList()
  },
  methods: {
    async getRecordList() {
      this.loading = true
      try {
        const res = await getUseCarRecordList(this.params)
        this.list = res.data.data
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      } finally {
        await this.sleep(300)
        this.loading = false
      }
    },

    openVehicleDialog(info) {
      this.vehicleInfo = info
      this.vehicleDialogShow = true
    },

    openExamineDrawer(row) {
      this.useCarRecordingDrawVisible = true
      this.currentRecording = row.id
    },

    handleExamine(e) {
      this.examineUseVehicleFetch(e)
    },

    async examineUseVehicleFetch(params) {
      const loading = this.openLoading()
      try {
        const res = await examineUseVehicle(params, this.currentRecording)
        this.$message.success('操作成功')
        this.refresh()
        this.useCarRecordingDrawVisible = false
      } catch (error) {
        this.$message.error('操作失败')
      } finally {
        loading.close()
      }
    },

    openLoading() {
      return this.$loading({
        lock: true,
        text: 'loading...',
        spinner: 'el-icon-loading'
      })
    },

    pagination(e) {
      this.params.page = e.page
      this.params.paginate = e.limit
      this.refresh()
    },

    handleSearch() {
      this.params.page = 1
      this.refresh()
    },

    resetSearch() {
      this.params = this.$options.data().params
      this.refresh()
    },

    refresh() {
      this.getRecordList()
    },

    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },

    timeFormat(time) {
      return !time ? '_' : dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },

    stateTagOptions(state) {
      const m = {
        wait: {
          label: '待审批',
          type: 'warning'
        },
        success: {
          label: '审批通过',
          type: 'success'
        },
        failed: {
          label: '审批失败',
          type: 'danger'
        },
        cancel: {
          label: '已撤销',
          type: 'info'
        }
      }

      return m[this.stateFormatter(state)]
    },

    stateFormatter(state) {
      if (state === null) return 'wait'

      if (state === 1) return 'success'

      if (state === 0) return 'failed'

      if (state === 2) return 'cancel'
    },

    handleDeleteRecord(id) {
      this.$confirm(
        '是否删除该项？',
        '提示',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      ).then(() => {
        this.deleteRecordFetch(id)
      })
    },

    async deleteRecordFetch(id) {
      try {
        await deleteVehicleRecords(id)
        this.$message.success('删除成功')
        this.params.page = 1
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '删除失败')
      }
    },

    handleCancelRecord(id) {
      this.$confirm(
        '是否撤销该项？',
        '提示',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      ).then(() => {
        this.cancelVehicleRecord(id)
      })
    },

    async cancelVehicleRecord(id) {
      try {
        await cancelVehicleRecords(id)
        this.$message.success('撤销成功')
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '撤销失败')
      }
    },

    editBtnVisible(row) {
      const status = this.stateFormatter(row?.review_status)
      const useTime = row?.vehicle_usage_time
      const nowTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      if ((status === 'success' || status === 'wait') && useTime > nowTime) {
        return true
      }
      return false
    },

    handleShowEditBtn(row) {
      console.log('row --------->', row)
      this.editCarUseInfo = {
        id: row?.id,
        user_name: row?.user?.username, // 申请人
        vehicle_usage_time: row?.vehicle_usage_time, // 用车时间
        vehicle_resources_id: row?.vehicle_resources_id, // 车辆id
        driver_type: row?.driver_type, // 司机类型
        driver_resources_id: row?.driver_type === 'notSelf' ? row?.drive_user_id
          : row?.driver_resources_id, // 司机id
        car_reason: row?.car_reason, // 用车事由
        vehicle_route: row?.vehicle_route, // 用车路线
        customer_name: row?.customer_name, // 客户姓名
        customer_phone: row?.customer_phone, // 客户电话
        remark: row?.remark // 备注
      }
      this.editCarUseVisible = true
    },

    handleEditCarUseConfirm(e) {
      console.log('e --------->', e)
      this.editCarUseFetch(e)
    },

    async editCarUseFetch(params) {
      try {
        const res = await editCarUseByAdmin(params)
        this.$message.success('修改成功')
        this.editCarUseVisible = false
        this.resetSearch()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      }
    }

  }
}
</script>

<style scoped lang='scss'>
.use-car {
  padding: 20px;

  .card {
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 20px;
    padding: 20px 20px 0 20px;
  }

  ::v-deep(.el-form-item) {
    margin-bottom: 20px;
    //margin-right: 20px;
  }

  .pagination {
    display: flex;
    justify-content: end;
  }
}

::v-deep(.el-card) {
  border: none;
}
</style>
